using GHIElectronics.NETMF.Glide;
using GHIElectronics.NETMF.Glide.UI;

namespace Melody_Glider.GUIContent
{
    class MainMenuWindow: WindowFrame
    {
        private readonly GUI _gui;
        private readonly SystemState _conditions;

        public MainMenuWindow(GUI gui, SystemState state)
        {
            _gui = gui;
            _conditions = state;
        }

        protected override void SophisticatedInit()
        {
            ThisWindow.BackImage = Resources.GetBitmap(Resources.BitmapResources.logo); //from scx.hu
            HideButtons();
        }

        protected override void InitButtons() //buttons to hashtable?
        {
            var newBtn = (Button)ThisWindow.GetChildByName("NewButton");
            newBtn.TapEvent += NewBtnTapEvent;

            var loadBtn = (Button)ThisWindow.GetChildByName("LoadButton");
            loadBtn.TapEvent += LoadBtnTapEvent;

            var ejectBtn = (Button)ThisWindow.GetChildByName("EjectButton");
            ejectBtn.TapEvent += EjectBtnTapEvent;
        }

        private void NewBtnTapEvent(object sender)
        {
            _gui.Cursor.BringToStart();
            _conditions.SetForNewFile();

            _gui.EditorWindow.SetToMain();
        }
        
        private void LoadBtnTapEvent(object sender)
        {
            _gui.LoadMenuWindow.SetToMain();
        }

        private void EjectBtnTapEvent(object sender)
        {
            USB.UnmountFileSystem();

            HideButtons();
            ThisWindow.Invalidate();

            _gui.DispMsg("You can eject USB drive safely");
        }

        public void HideButtons()
        {
            ToggleButton("NewButton", false);
            ToggleButton("LoadButton", false);
            ToggleButton("EjectButton", false);
        }

        public void ShowButtons()
        {
            ToggleButton("NewButton", true);
            ToggleButton("LoadButton", true);
            ToggleButton("EjectButton", true);

            ThisWindow.Invalidate(); //it can contain this in opposite of HideButtons, because this is invoked only once, when MainMenuWindow is set to main
        }

        private void ToggleButton(string buttonName, bool enabled)
        {
            var btn = (Button)ThisWindow.GetChildByName(buttonName);
            btn.Visible = enabled;
        }

        public void DispMsg(string entry)
        {
            var text = (TextBlock)ThisWindow.GetChildByName("statusLabel");
            ThisWindow.FillRect(text.Rect);
            text.Text = entry;
            text.Invalidate();
        }

        public bool IsMain()
        {
            return Glide.MainWindow == ThisWindow;
        }
    }
}
